package org.sbbs.security.webapp.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.dispatcher.Dispatcher;
import org.sbbs.base.webapp.action.BaseMaintainAction;
import org.sbbs.security.model.Menu;
import org.sbbs.security.model.UrlResource;
import org.sbbs.security.service.MenuManager;
import org.sbbs.security.service.UrlResourceManager;

import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;

public class UrlResourceMaintainAction extends BaseMaintainAction<UrlResource, Long> {

	/**
     *
     */
	private static final long serialVersionUID = 2332788763668956953L;

	public String add() {
		try {
			this.model = new UrlResource();
			this.setEditTypeAdd();
			return SUCCESS;
		} catch (Exception e) {

			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));

		}
	}

	public String edit() {
		try {
			this.model = this.urlResourceManager.find(this.getId());
			this.setEditTypeEdit();
			return SUCCESS;
		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));
		}
	}

	public String save() {
		try {
			this.urlResourceManager.save(this.getModel());
			return this.ajaxReturn.success(getText((isNew()) ? "demoEntity.added" : "demoEntity.updated",
					"no msg key found,save successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.saved", new String[] { e.getMessage() }));
		}
	}

	public String makeToMenu() {
		try {
			String[] sIds = this.getIds().split(",");

			Long[] lIds = new Long[sIds.length];
			for (int i = 0; i < sIds.length; i++) {
				lIds[i] = Long.parseLong(sIds[i]);
			}

			UrlResource[] au = this.urlResourceManager.find(lIds);

			for (int i = 0; i < au.length; i++) {
				UrlResource u = au[i];
				if (!u.getIsMenuUrl()) {
					Menu m = new Menu();
					m.setTitle(u.getName());
					m.setUrlResource(u);
					this.menuManager.save(m);
				}
			}

			this.menuManager.reBuildAllTree();

			return this.ajaxReturn.success(getText((isNew()) ? "demoEntity.deleted" : "demoEntity.updated",
					"no msg key found,save successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.deleted", new String[] { e.getMessage() }));
		}
	}

	public String delete() {
		try {
			String[] sIds = this.getIds().split(",");

			Long[] lIds = new Long[sIds.length];
			for (int i = 0; i < sIds.length; i++) {
				lIds[i] = Long.parseLong(sIds[i]);
			}

			this.urlResourceManager.removeByIds(lIds);

			return this.ajaxReturn.success(getText((isNew()) ? "demoEntity.deleted" : "demoEntity.updated",
					"no msg key found,save successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.deleted", new String[] { e.getMessage() }));
		}

	}

	private UrlResourceManager urlResourceManager;
	private MenuManager menuManager;

	public void setUrlResourceManager(UrlResourceManager urlResourceManager) {
		this.urlResourceManager = urlResourceManager;
	}

	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}

	// @Valid
	private UrlResource model;

	public UrlResource getModel() {
		return model;
	}

	public void setModel(UrlResource model) {
		this.model = model;
	}

	public String initUrlResourceRepo() {
		try {
			List resList = this.urlResourceManager.findAll();

			Map rsMap = new HashMap();

			for (Iterator iterator = resList.iterator(); iterator.hasNext();) {
				UrlResource res = (UrlResource) iterator.next();
				// res.setId(null);
				rsMap.put(res.getUrl(), res);

			}

			Dispatcher dispatcher = Dispatcher.getInstance();
			ConfigurationManager cm = dispatcher.getConfigurationManager();
			Configuration cf = cm.getConfiguration();
			RuntimeConfiguration rc = cf.getRuntimeConfiguration();
			Map<String, Map<String, ActionConfig>> d = rc.getActionConfigs();
			Set nc = d.keySet();
			for (String key1 : d.keySet()) {
				if (!key1.equalsIgnoreCase("") && !key1.equalsIgnoreCase("/config-browser")) {
					System.out.println(key1);
					/*
					 * if (key1.equalsIgnoreCase("/")) { key1 = key1; } else {
					 * key1 = key1 + "/"; }
					 */
					Map<String, ActionConfig> a = d.get(key1);
					for (String key2 : a.keySet()) {
						System.out.println(key2);

						UrlResource res = new UrlResource();
						res.setNameSpace(key1);

						if (key1.equalsIgnoreCase("/")) {
							res.setUrl(key1 + key2);
						} else {
							res.setUrl(key1 + "/" + key2);
						}
						res.setName(this.getText(key2 + ".title", key2));

						if (!rsMap.containsKey(key1 + key2)) {
							rsMap.put(res.getUrl(), res);
						}
						// ActionConfig ac = a.get(key2);
					}
				}
			}

			this.urlResourceManager.initUrlResourceRepo(new ArrayList(rsMap.values()));

			return this.ajaxReturn.success("init success");

		} catch (Exception e) {
			return this.ajaxReturn.error("init fail");
		}

	}
}
